package com.david.func_test.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.updateLayoutParams
import androidx.viewpager2.widget.ViewPager2
import com.david.func_test.R

/**
 * 小于等于4个tab时的平分屏幕layout
 */
class NoScrollTabLayout: FrameLayout {

    constructor(context: Context, attributeSet: AttributeSet): super(context, attributeSet)
    private val tabs: ArrayList<TabBean> = ArrayList()

    val bgView: View = View(context)

    var tabWidth = 0

    private var viewPager2: ViewPager2? = null

    private var tabSelectFunc: ((Int) -> Unit)? = null


    private val tabClickListener:OnClickListener = OnClickListener { v ->
        v?.let {
            if (it.tag is Int) {
                val position = v.tag as Int
                viewPager2?.currentItem = position
                tabSelectFunc?.invoke(position)
            }
        }
    }

    init {
        bgView.setBackgroundResource(R.drawable.message_top_selecttab_bg)
        addView(bgView)
    }

    private val onPageChangeCallback: ViewPager2.OnPageChangeCallback = object :
        ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
        }

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int
        ) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            bgView.updateLayoutParams<MarginLayoutParams> { leftMargin =
                (tabWidth* position + tabWidth * positionOffset).toInt()
            }
        }
    }

    fun setupWithViewPager2(viewPager2: ViewPager2){
        viewPager2.registerOnPageChangeCallback(onPageChangeCallback)
        this.viewPager2 = viewPager2
    }

    /**
     * 动态从外部设置tabs
     */
    fun setTabs(tempTabs: ArrayList<TabBean>){
        tabs.clear()
        removeAllViews()
        tempTabs.forEach {
            tabs.add(it)
        }

        if (width > 0) {
            setTabView()
        }
    }

    private fun setTabView(){
        tabWidth = measuredWidth/tabs.size

        repeat(tabs.size) {
            val tab = LayoutInflater.from(context).inflate(R.layout.item_layout_tab, this, false)
            val params = LayoutParams(tabWidth, LayoutParams.MATCH_PARENT)
            params.marginStart = it * tabWidth
            tab.layoutParams = params
            addView(tab)

            tab.tag = it
            tab.setOnClickListener(tabClickListener)
        }

        bgView.layoutParams = LayoutParams(tabWidth, LayoutParams.MATCH_PARENT)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (bgView.layoutParams.width <= 0) {
            setTabView()
        }
    }
}

class TabBean{
    var title: String = "title"
}